var express = require('express');
var router = express.Router();
var EventProxy = require('eventproxy');
var util = require('util');

var logger = require("../models/logger");
var newPerson = require("../models/NewPerson");
var resultJson = require("../result-json");
var Utils = require("../utils");
var Consts = require("../consts");
var User = require("../models/User");

router.post('/', function(req, res) {
    res.send('respond with a resource');
});


//根据id查询详情
router.post("/detail", function(req, res) {
    var newperson = req.body;
    newPerson.findById(newperson._id, function(err, newperson) {
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        if (!newperson)
            return res.send(resultJson(200));
        
        newperson = JSON.parse(JSON.stringify(newperson));
        User.findOne({
            "_id": newperson.from
        }, function(err, user) {
            if (err || !user)
                return res.send(resultJson(3));

            newperson.user = user;
            res.send(resultJson(0, newperson));
        });
    });
});

router.post('/upsert', function(req, res) {
    var newperson = req.body;
    newperson.create = new Date();
    var _id = newperson._id;
    if (newperson._id) {
        delete newperson._id;
        newPerson.update({
            _id:_id,
        }, {
            $set: newperson
        }).exec(function(err) {
            if (err) {
                logger.error(err);
                return res.send(resultJson(2));
            }
            res.send(resultJson(0));
        });
    } else {
        newperson.from = newperson._user._id;
        new newPerson(newperson).save(function(err, newperson) {
            if (err) {
                logger.error(err);
                return res.send(resultJson(2));
            }
            res.send(resultJson(0, newperson));
        });
    }
});

router.post('/bj', function(req, res) {
    list(req, res);
});
router.post('/sh', function(req, res) {
    list(req, res);
});
router.post('/gz', function(req, res) {
    list(req, res);
});
router.post('/sz', function(req, res) {
    list(req, res);
});
router.post('/qt', function(req, res) {
    list(req, res);
});

function list (req, res) {
    var newperson = req.body;
    var proxy = new EventProxy();
    proxy.all("results", "count", function(results, count) {
        res.send(resultJson(0, {
            results: results,
            count: count
        }))
    })
    var start = newperson.start || 0;
    var count = newperson.count || Consts.MAX;
    var option = {};
    if (newperson.from)
        option.from = newperson.from;
    if(newperson.category)
        option.category = newperson.category;
    if(newperson.aTo)
        option.aTo = newperson.aTo;
    newPerson.find(option).skip(start).limit(count).sort({
        create: -1
    }).exec(function(err, events) {
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        var events = JSON.parse(JSON.stringify(events));
        var index = 0;
        fromName(res, index, events, proxy);
    });
    newPerson.find(option).count(function(err, num) {
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        proxy.emit("count", num);
    });
};

router.post('/list', function(req, res) {
    var newperson = req.body;
    var proxy = new EventProxy();
    proxy.all("results", "count", function(results, count) {
        res.send(resultJson(0, {
            results: results,
            count: count
        }))
    })
    var start = newperson.start || 0;
    var count = newperson.count || Consts.MAX;
    var option = {};
    if (newperson.from)
        option.from = newperson.from;
    if(newperson.category)
        option.category = newperson.category;
    if(newperson.aTo)
        option.aTo = newperson.aTo;
    newPerson.find(option).skip(start).limit(count).sort({
        create: -1
    }).exec(function(err, events) {
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        var events = JSON.parse(JSON.stringify(events));
        var index = 0;
        fromName(res, index, events, proxy);
    });
    newPerson.find(option).count(function(err, num) {
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        proxy.emit("count", num);
    });
});

function fromName(res, index, events, proxy) {
    if (index == events.length || events.length == 0) {
        proxy.emit("results", events);
    } else {
        if(!events[index].name) {
            User.findOne({
                "_id": events[index].from
            }, function(err, user) {
                if (err) {
                    logger.error(err);
                    return res.send(resultJson(2));
                }
                if (!user)
                    user = {};

                events[index].name = user.name;
                index++;
                fromName(res, index, events, proxy);
            });            
        }else {
            index++;
            fromName(res, index, events, proxy);            
        }
    }
};

//删除
router.post('/remove', function(req, res) {
    var newperson = req.body;
    console.log(newperson);
    var _id = newperson._id;
    console.log("_id:"+_id);
    newPerson.remove({
        _id: _id
    }, function(err) {
        if (err) {
            logger.error(err);
            res.send(resultJson(2));
        } else
            res.send(resultJson(0));
    });
});


router.post("/views", function(req, res) {
    var newperson = req.body;
    var _id=newperson._id;
    newPerson.findById(newperson._id, function(err, newpersons) {
        if (err ) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        if(newperson.view==null){
            newPerson.update({
                _id: _id
            }, {
                $set: {
                    view: 1
                }
            }, function(err) {
                if (err)
                    return res.send(resultJson(2));
                console.log("news.view:"+newperson.view);
                res.send(resultJson(0, newpersons));
            }); 
            return;
        }else{
           newPerson.update({
                _id: _id
            }, {
                $set: {
                    view:++newperson.view
                }
            }, function(err) {
                if (err)
                    return res.send(resultJson(2));
                console.log("news.view:"+newperson.view);
                res.send(resultJson(0, newpersons));
            });
        }
    });
});


module.exports = router;